<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        html,
        body {
            margin: 0;
            height: 100%;
        }

        #box {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
            top: 100px;
            left: 100px;
        }
    </style>
</head>

<body>
    <div id="box"></div>
    <script>
        window.onload = function () {
            var box = document.getElementById('box');
            box.onmousedown = function (ev) {
                var oEvent = ev || window.event; // 兼容火狐,火狐下没有window.event
                var distanceX = oEvent.clientX - box.offsetLeft; // 鼠标到可视区左边的距离 - box到页面左边的距离
                var distanceY = oEvent.clientY - box.offsetTop;
                console.log('鼠标离盒子左上角的距离(鼠标到可视区左上角的距离 - box到页面左上角到可视区的距离)',distanceX,distanceY)
                document.onmousemove = function (ev) {
                    // console.log(ev)
                    var oEvent = ev || window.event;
                    var left = oEvent.clientX - distanceX;//鼠标到可视区左上角距离-鼠标最开始到盒子左上角的距离
                    console.log("left",left)
                    var top = oEvent.clientY - distanceY;
                    console.log("top",top)
                    if (left <= 0) {
                        left = 0;
                    } else if (left >= document.documentElement.clientWidth - box.offsetWidth) {
                        left = document.documentElement.clientWidth - box.offsetWidth;
                    }
                    if (top <= 0) {
                        top = 0;
                    } else if (top >= document.documentElement.clientHeight - box.offsetHeight) {
                        top = document.documentElement.clientHeight - box.offsetHeight;
                    }
                    box.style.left = left + 'px';
                    box.style.top = top + 'px';
                }
                document.onmouseup = function () {
                    document.onmousemove = null;
                    box.onmouseup = null;
                }
            }
        }
    </script>
</body>

</html>